package com.artron.mediaartron.ui.fragment.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.artron.baselib.adapter.recyclerview.BaseViewHolder;
import com.artron.baselib.adapter.recyclerview.CommonAdapter;
import com.artron.baselib.adapter.recyclerview.DividerItemDecoration;
import com.artron.baselib.base.BaseLoadingFragment;
import com.artron.baselib.base.BaseStaticFragment;
import com.artron.baselib.entity.Response;
import com.artron.baselib.ui.LoadingPage;
import com.artron.mediaartron.R;
import com.artron.mediaartron.data.config.AppProfile;
import com.artron.mediaartron.data.entity.AddressData;
import com.artron.mediaartron.data.net.RetrofitHelper;
import com.artron.mediaartron.ui.activity.GeneralActivity;
import com.artron.mediaartron.ui.widget.SwipeItemLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import static android.R.attr.data;

/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-10-23.
 */

public class OrderAddressFragment extends BaseLoadingFragment<List<AddressData>> {

    private static final String TAG = "OrderAddressFragment";

    @BindView(R.id.OrderAddressFragment_recycler)
    protected RecyclerView mRecyclerView;
    @BindView(R.id.OrderAddressFragment_btn_add)
    protected Button mBtnAddAddress;
    private List<AddressData> mFragmentData = new ArrayList<>();
    private CommonAdapter<AddressData> mCommonAdapter;

    public static OrderAddressFragment newInstance() {
        Bundle args = new Bundle();
        OrderAddressFragment fragment = new OrderAddressFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        show();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_order_address;
    }

    @Override
    protected void initView() {
        mBtnAddAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GeneralActivity.startForResult(mContext, GeneralActivity.ORDER_ADD_ADDRESS, "新建地址");
            }
        });
        //初始化列表UI
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext,
                LinearLayoutManager.VERTICAL, false));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL_LIST,
                R.color.gray_e3));
        mRecyclerView.addOnItemTouchListener(new SwipeItemLayout.OnSwipeItemTouchListener(mContext));

        mCommonAdapter = new CommonAdapter<AddressData>(mContext, R.layout.item_address_list,
                mFragmentData)  {

            @Override
            public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder holder = super.onCreateViewHolder(parent, viewType);
                ClickListener clickListener = new ClickListener(holder);
                holder.setOnClickListener(R.id.ItemAddressList_btn_set_default, clickListener);
                holder.setOnClickListener(R.id.ItemAddressList_btn_delete, clickListener);
                holder.setOnClickListener(R.id.ItemAddressList_iv_edit, clickListener);
                holder.setOnClickListener(R.id.ItemAddressList_rl_content, clickListener);
                return holder;
            }

            @Override
            protected void convert(BaseViewHolder holder, AddressData data, int position) {
                boolean isDefault = "Y".equals(data.getIsDefault());
                int textColor = isDefault ? R.color.order_purple : R.color.gray_33;
                String detail = String.format("%s-%s-%s-%s", data.getProvinceName(), data.getCityName(),
                        data.getDistrictName(), data.getDetail());

                holder.setVisible(R.id.ItemAddressList_iv_default, isDefault)
                        .setVisible(R.id.ItemAddressList_tv_tag, isDefault)
                        .setTextColorRes(R.id.ItemAddressList_tv_name, textColor)
                        .setTextColorRes(R.id.ItemAddressList_tv_tel_num, textColor)
                        .setText(R.id.ItemAddressList_tv_name, data.getName())
                        .setText(R.id.ItemAddressList_tv_tel_num, data.getMobileCode())
                        .setText(R.id.ItemAddressList_tv_detail, detail);
            }

            class ClickListener implements View.OnClickListener {

                private BaseViewHolder mBaseViewHolder;

                ClickListener(BaseViewHolder holder) {
                    this.mBaseViewHolder = holder;
                }
                @Override
                public void onClick(View v) {
                    int position = mBaseViewHolder.getAdapterPosition();
                    AddressData data = mFragmentData.get(position);
                    switch (v.getId()) {
                        case R.id.ItemAddressList_btn_set_default:
                            AddressData firstData = mFragmentData.get(0);
                            firstData.setIsDefault("N");
                            data.setIsDefault("Y");
                            dataFilter(mFragmentData);
                            dataFilter(mDatas);
                            notifyItemChanged(position);
                            notifyItemChanged(0);
                            moveItem(position, 0);
                            RetrofitHelper.getOrderAddressApi().updateDefaultAddress(data.getId())
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Action1<Response>() {
                                    @Override
                                    public void call(Response response) {
                                        Log.d(TAG, "call: " + response);
                                    }
                                });

                            break;
                        case R.id.ItemAddressList_btn_delete:
                            mFragmentData.remove(position);
                            deleteItem(position);
                            RetrofitHelper.getOrderAddressApi().deleteAddress(data.getId())
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new Action1<Response>() {
                                        @Override
                                        public void call(Response response) {
                                            Log.d(TAG, "call: " + response);
                                        }
                                    });
                            break;
                        case R.id.ItemAddressList_iv_edit:
                            data.setPosition(position);
                            GeneralActivity.startForResult(mContext, GeneralActivity.ORDER_ADD_ADDRESS,
                                "新建地址", data);
                            break;
                        case R.id.ItemAddressList_rl_content:
                            Intent intent = new Intent();
                            intent.putExtra(GeneralActivity.CONTENT, data);
                            getActivity().setResult(GeneralActivity.RESULT_OK, intent);
                            getActivity().finish();
                            break;
                    }
                }
            }
        };
        mRecyclerView.setAdapter(mCommonAdapter);
    }

    @Override
    public void initViewWithData(List<AddressData> data) {
        if (data == null) {
            return;
        }

        mFragmentData = data;

        dataFilter(mFragmentData);
        mCommonAdapter.setItems(data);
    }

    @Override
    protected Observable<Response<List<AddressData>>> retrofitData() {
        String passId = AppProfile.getUserInfo().getPassId();
        return RetrofitHelper.getOrderAddressApi().queryAddress(passId);
    }

    private void dataFilter(List<AddressData> dataList) {
        AddressData data = null;
        for (AddressData addressData : dataList) {
            if ("Y".equals(addressData.getIsDefault())) {
                data = addressData;
                break;
            }
        }
        if (data == null) {
            return;
        }
        dataList.remove(data);
        dataList.add(0, data);
    }

    public void setItem(AddressData data) {
        int position = data.getPosition();
        if (position == -1) {
            mFragmentData.add(data);
            mCommonAdapter.addItem(data);
            mRecyclerView.scrollToPosition(mFragmentData.size() - 1);
        } else {
            mFragmentData.set(position, data);
            mCommonAdapter.setItem(data.getPosition(), data);
            if ("Y".equals(data.getIsDefault()) && position != 0) {
                AddressData firstData = mFragmentData.get(0);
                firstData.setIsDefault("N");
                dataFilter(mFragmentData);
                dataFilter(mCommonAdapter.getData());
                mCommonAdapter.notifyItemChanged(position);
                mCommonAdapter.notifyItemChanged(0);
                mCommonAdapter.moveItem(position, 0);
            }
        }
    }

    @Override
    public boolean onBackPressed() {
        AddressData addressData = null;
        if (mFragmentData != null && mFragmentData.size() > 0) {
            addressData = mFragmentData.get(0);
        } else {
            addressData = new AddressData();
        }
        Intent intent = new Intent();
        intent.putExtra(GeneralActivity.CONTENT, addressData);
        getActivity().setResult(GeneralActivity.RESULT_OK, intent);
        getActivity().finish();
        return true;
    }

    @Override
    protected LoadingPage.LoadResult checkData(List<AddressData> data) {
        return LoadingPage.LoadResult.Success;
    }
}
